package com.example.wlzz.service.serviceImpl;

import com.example.wlzz.dto.TaskDTO;
import com.example.wlzz.dto.admin.RoleDTO;
import com.example.wlzz.entity.UserInfo;
import com.example.wlzz.entity.admin.UserWithRole;
import com.example.wlzz.entity.mongoEntity.LoveTask;
import com.example.wlzz.entity.mongoEntity.Task;
import com.example.wlzz.entity.mongoEntity.TaskReceive;
import com.example.wlzz.enums.AdminEnum;
import com.example.wlzz.enums.Del_flagEnum;
import com.example.wlzz.form.RegisterForm;
import com.example.wlzz.repository.*;
import com.example.wlzz.repository.mapper.admin.RoleMapper;
import com.example.wlzz.repository.mongoRepository.TaskReceiveRepository;
import com.example.wlzz.repository.mongoRepository.TaskRepository;
import com.example.wlzz.service.AdminService;
import com.example.wlzz.service.UserService;
import com.example.wlzz.utils.ResultVOUtil;
import com.example.wlzz.vo.LoginUserInfoVO;
import com.example.wlzz.vo.PageVO;
import com.example.wlzz.vo.ResultVO;
import com.example.wlzz.vo.TaskVO;
import com.mongodb.client.MongoCollection;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService{
    @Autowired
    private UserService userService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private TaskRepository taskRepository;
    @Autowired
    private TaskServiceImpl taskServiceImpl;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private TaskReceiveRepository taskReceiveRepository;
    @Override
    public ResultVO login(RegisterForm registerForm) {
       ResultVO resultVO =  userService.login(registerForm);
       if(resultVO.getCode().equals(0)){  //说明过了正常登陆
           log.info("【后台管理登陆】账号正常通过普通校验：phone={}",registerForm.getPhone());
           RoleDTO roleDTO = roleMapper.getRoleName(registerForm.getPhone());
           if(roleDTO.getRole_name().equals("超级管理员")|roleDTO.getRole_name().equals("普通管理员")){   //管理员的角色  --> 超级管理员一般不允许修改自己的权限，默认全都拥有
                return ResultVOUtil.success();
           }else{
               log.error("【后台管理登陆】无权限进入：phone={}",registerForm.getPhone());
               return ResultVOUtil.error(AdminEnum.NO_PERMISSSION.getCode(),AdminEnum.NO_PERMISSSION.getMessage());
           }
       }else{
           log.error("【后台管理登陆】后台账号密码输入错误：phone={}",registerForm.getPhone());
           return resultVO;
       }
    }
    @Override
    public PageVO findAll_task(Pageable pageable,int status) {
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");   //降序----根据创建时间来进行降序
        PageRequest request =  PageRequest.of(pageable.getPageNumber(),pageable.getPageSize(),sort);
        Page<Task> taskPage = taskRepository.findByDelFlag(status,request);
        List<TaskDTO> taskDTOS = new ArrayList<>();
        MongoCollection<Document> loveTaskCollection =  mongoTemplate.getCollection("loveTask");
        MongoCollection<Document> commentCollention =  mongoTemplate.getCollection("comment");
        for (Task task : taskPage.getContent()) {
            TaskDTO taskDTO = new TaskDTO();
            BeanUtils.copyProperties(task,taskDTO);
            Long getTime = task.getCreateTime().getTime();
            taskDTO.setCreateTime(getTime.toString());
            taskDTOS.add(taskDTO);
        }
        List<TaskVO> taskVOList = new ArrayList<>();
        for (TaskDTO taskDTO : taskDTOS) {
            TaskVO taskVO = new TaskVO();
            UserInfo userInfo = userInfoRepository.findByUserId(taskDTO.getUserid());
            taskVO.setNickName(userInfo.getNickName());
            taskVO.setImgUrl(userInfo.getImgUrl());
            taskVO.setTask(taskDTO);
            Document document1 = new Document();
            document1.put("taskId",taskDTO.get_id());
            Document document2 = new Document();  //comment的条件
            document2.put("taskId",taskDTO.get_id());
            document2.put("delFlag",status);
            Long count =  loveTaskCollection.count(document1);
            taskVO.setLove(count.intValue());
            taskVO.setUserid(taskDTO.getUserid());
            Long commentCount =  commentCollention.count(document2);
            taskVO.setCommentCount(commentCount.intValue());
            //增加接单者
            if(taskDTO.getStatus()!=0){  //表示已被接单
                TaskReceive receive =  taskReceiveRepository.findByTaskIdAndStatus(taskVO.getTask().get_id(),taskDTO.getStatus());
                UserInfo re_userInfo = userInfoRepository.findByUserId(receive.getUserid());
                taskVO.setRe_imgUrl(re_userInfo.getImgUrl());
                taskVO.setRe_nickName(re_userInfo.getNickName());
                taskVO.setRe_userid(re_userInfo.getUserId());
            }

            taskVOList.add(taskVO);
        }
        PageVO pageVO = new PageVO();
        pageVO.setCurrentPage(pageable.getPageNumber());
        pageVO.setDataList(taskVOList);  //重新封装数据
        pageVO.setSize(pageable.getPageSize());
        return pageVO;
    }
}
